package com.kaisu.blog.web.handler;

import com.kaisu.blog.application.exception.TokenExpireException;
import com.kaisu.blog.common.exceptions.InternalException;
import com.kaisu.blog.web.result.Result;
import com.kaisu.blog.web.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author kaisu
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> exception(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return Result.fail(ResultCode.FAIL.getCode(), "内部错误！");
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> accessDeniedException(AccessDeniedException e) {
        log.error("权限异常信息 ex={}", e.getMessage(), e);
        return Result.fail(ResultCode.NO_AUTH.getCode(), "您无权限访问该接口！");
    }

    @ExceptionHandler(TokenExpireException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> tokenExpireDeniedException(TokenExpireException e) {
        log.error("令牌异常信息 ex={}", e.getMessage(), e);
        return Result.fail(ResultCode.TOKEN_EXPIRE.getCode(), "令牌无效");
    }

    @ExceptionHandler(InternalException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> internalException(InternalException exception) {
        log.error("错误信息：", exception);
        return Result.fail(ResultCode.FAIL.getCode(), exception.getMessage());
    }
}